package top.laoshuzi.server.userservice.server;

import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import top.laoshuzi.server.userservice.service.UserService;

@Component
public class ThriftServiceRunner implements CommandLineRunner {

    @Value("${thrift.user-service.port}")
    private int userServicePort;

    @Autowired
    private UserService.Iface userService;

    @Override
    public void run(String... args) throws Exception {

        new Thread(new Runnable() {
            @Override
            public void run() {
                start();
            }
        }).start();
    }

    private void start() {
        TProcessor processor = new UserService.Processor<>(userService);

        TNonblockingServerSocket serverSocket = null;
        try {
            serverSocket = new TNonblockingServerSocket(userServicePort);
        } catch (TTransportException e) {
            e.printStackTrace();
        }

        TNonblockingServer.Args arg = new TNonblockingServer.Args(serverSocket);
        arg.processor(processor);
        arg.transportFactory(new TFramedTransport.Factory());
        arg.protocolFactory(new TBinaryProtocol.Factory());

        TServer server = new TNonblockingServer(arg);
        server.serve();
    }
}
